#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    initSeialPort();
}

MainWindow::~MainWindow()
{
    serial->close();
    delete ui;
}

void MainWindow::initSeialPort()
{

    serial = new QSerialPort("COM3");
    serial->open(QIODevice::ReadWrite);
    serial->setBaudRate(QSerialPort::Baud9600);
    serial->setDataBits(QSerialPort::Data8);
    serial->setParity(QSerialPort::NoParity);
    serial->setStopBits(QSerialPort::OneStop);
    serial->setFlowControl(QSerialPort::NoFlowControl);
    connect(serial,SIGNAL(readyRead()),this,SLOT(serialRead()));
    connect(ui->pushButton,SIGNAL(pressed()),this,SLOT(slotsPtn()));
}

QString MainWindow::js()
{
    return QString::number(ui->lcdNumber->value() / ui->label->text().toDouble(),'f', 0);
}

void MainWindow::serialRead()
{
    static QByteArray allData;
    while (!serial->atEnd()) {
        QByteArray dataTemp = serial->readAll();
        //qCritical() << dataTemp;
        if( dataTemp.data()[15] == 'g'){
            allData += dataTemp;
            allData.resize(18);
        }
        else
            allData += dataTemp;
    }

    if(allData.size() == 18){
        if(QString(allData.at(0))+QString(allData.at(1)) == "ST"){
            if(QString(allData.at(3))+QString(allData.at(4)) == "TR"){
                QString TR =  QString(allData.at(7))
                                +QString(allData.at(8))
                                +QString(allData.at(9))
                                +QString(allData.at(10))
                                +QString(allData.at(11))
                                +QString(allData.at(12))
                                +QString(allData.at(13));
                ui->lcdNumber->display(TR);
                qCritical() << TR.toDouble();
                ui->label_2->setText(js());
            }
        }
    }

    allData.clear();

}

void MainWindow::slotsPtn()
{
    ui->label->setText(QString::number(ui->lcdNumber->value()));
}
